﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;

namespace LinqToFileSystem
{
    public static class DirectoryInfoExtensions
    {
        /// <summary>
        /// An enumeration of files within a directory.
        /// </summary>
        /// <param name="dir"></param>
        /// <returns></returns>
        public static IEnumerable<FileInfo> Files(this DirectoryInfo dir)
        {            
            return dir.GetFiles().AsEnumerable();
        }
    }

    /// <summary>
    /// Adapts a DirectoryInfo to provide methods required for generate
    /// a Linq To Tree API
    /// </summary>
    class FileSystemTreeAdapter : ILinqTree<DirectoryInfo>
    {
        private DirectoryInfo _dir;

        public FileSystemTreeAdapter(DirectoryInfo dir)
        {
            _dir = dir;                   
        }

        public IEnumerable<DirectoryInfo> Children()
        {
            DirectoryInfo[] dirs = null;
            try
            {
                dirs = _dir.GetDirectories();
            }
            catch (Exception)
            { }

            if (dirs == null)
            {
                yield break;
            }
            else
            {
                foreach (var item in dirs)
                    yield return item;
            }
        }

        public DirectoryInfo Parent
        {
            get
            {
                return _dir.Parent;
            }
        }

    }
}
